package com.gao.mybatis.session;

import com.gao.mybatis.configuration.Configuration;
import com.gao.mybatis.executor.DefaultExecutor;
import com.gao.mybatis.executor.Executor;
import com.gao.mybatis.mapperproxy.MapperProxyFactory;
import com.gao.mybatis.resource.ClassPathResources;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.SQLException;
import java.util.List;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2020-03-29 18:29
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String stateId, Object... params) throws Exception {
        Executor executor = new DefaultExecutor();
        return executor.query(configuration, configuration.getStatementMap().get(stateId), params);
    }

    @Override
    public <T> T selectOne(String stateId, Object... params) throws Exception {
        List<T> list = selectList(stateId, params);
        if (list.size() >1) {
            throw  new RuntimeException("获取的数据太多");
        }
        if(list.size()==1){
            return list.get(0);
        }
        return null;

    }

    @Override
    public <T> T getMapper(Class<T> type) throws Exception {

        MapperProxyFactory<T> factory = new MapperProxyFactory<>(type);

        return factory.newInstance(this);
    }

    @Override
    public Configuration getConfiguration() {
        return this.configuration;
    }
}
